package com.ccf.business.knowledge.controller;

import lombok.SneakyThrows;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 描述：
 * 过滤器异常统一处理
 *  参考{@link BasicErrorController}
 *  不是很好的解决办法 但是主要因为这个类只有@RestController标签才生效
 * @author xianggj
 * @Date 2022/2/18 15:46
 **/
@RestController
public class FilterErrorController extends BasicErrorController {


    private static ErrorProperties initPerproties(){
        ErrorProperties errorProperties = new ErrorProperties();
        errorProperties.setIncludeMessage(ErrorProperties.IncludeAttribute.ALWAYS);
        return errorProperties;
    }

    public FilterErrorController() {
        super(new DefaultErrorAttributes(), initPerproties());
    }

    @Override
    public String getErrorPath() {
        return null;
    }


    @SneakyThrows
    @Override
    public ErrorAttributeOptions getErrorAttributeOptions(HttpServletRequest request, MediaType mediaType) {
        if (request.getAttribute("javax.servlet.error.exception") != null){
            throw (Exception)request.getAttribute("javax.servlet.error.exception");
        }
        return super.getErrorAttributeOptions(request, mediaType);
    }


}
